import json
import requests
import time

from src.utils.config import config, logger
from src.utils.util import sending_exception


BASE_URL = 'http://{}:{}/price/test'


class APIHealthChecker:
    def __init__(self):
        self.server_ip = json.loads(
            config.get_config('model', 'model_servers'))
        self.api_ports = json.loads(
            config.get_config('model', 'model_server_ports'))

    def check_api_health(self):
        """
        检查API接口健康状态
        :return:
        """
        for ip in self.server_ip:
            for port in self.api_ports:
                logger.info('checking health api@{}:{}'.format(ip, port))
                request_url = BASE_URL.format(ip, port)
                response = requests.get(request_url)
                if response.status_code == 200:
                    logger.info(
                        'api@{}:{} health check successfully'.format(ip, port))
                else:
                    sending_exception('API 接口@{}:{} 健康检查失败！'.format(ip, port))

                time.sleep(1)
